﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Collections;
using CharitiesLib;
using Charities.ModelViews;
using Microsoft.Office.Interop;
using System.Reflection;
using System.IO;
using iTextSharp.text.pdf;
using iTextSharp.text;
using System.Drawing.Printing;

namespace Charities.Forms
{
    public partial class TrackWorthyUserForm : Form
    {
        int userid;
        public bool is_loaded;
        Form fo;
        public TrackWorthyUserForm(int uid ,Form m)
        {
            fo = m;
            userid = uid;
            MdiParent = m;
            InitializeComponent();
        }
        ModelContainer ctx = new ModelContainer();
        private void TrackWorthyUserForm_Load(object sender, EventArgs e)
        {
            // add this form to window list
            ((Forms.FormMDI)fo).addFormToWindowsList(this); 
            is_loaded = true;
            GetWorthiesNames();
        }
        int? worthyId;
        private void GetWorthiesNames()
        {
            List<WorthiesView> q = new List<WorthiesView>();
            if (tabControl1.SelectedTab == tabPageByWorthy)
            {
                var qworthy = (from p in ctx.People
                         join w in ctx.Worthies
                         on p.Id equals w.PersonId
                         where w.IsActive == true
                         select new ModelViews.WorthiesView
                         {
                             Id = w.Id,
                             DisplayName = p.FirstName + " " + p.FatherName + " " + p.LastName,
                             insertDate = w.InsertDate,
                             PhoneNumber = w.Phone,
                             CurrentAddress = w.CurrentAddress,
                             OreginalAddress = w.OriginalAddress,
                             WorthyTypeName = w.WorthyType.Name,
                             NatNumber = p.NationalNumber,
                             FamilyNumber = w.FamilyNumber

                         });
                q = qworthy.ToList();
            }
            else if (tabControl1.SelectedTab == tabPageByUser)
            {
                var quser = (from u in ctx.Users
                             select new WorthiesView
                                 {
                                     Id = u.Id,
                                     DisplayName =u.username,
                                 });
                q = quser.ToList();
            }
            
            if (txb_search.Text.Length == 0)
            {
                if(tabControl1.SelectedTab==tabPageByWorthy)
                listBoxWorthies.DataSource = q.ToArray();
                if (tabControl1.SelectedTab == tabPageByUser)
                    ListBoxUsers.DataSource = q.ToArray();
            }
            else
            {
                ArrayList arr = new ArrayList();
                string[] srch = txb_search.Text.ToLower().Split(' ');
                foreach (string qry in srch)
                {
                    if (qry.Length != 0)
                    {
                        int id;
                        DateTime dt;
                        if (Int32.TryParse(qry, out id))
                        {
                            arr.AddRange(q.Where(c => c.Id == id || c.FamilyNumber.Contains(qry) ||
                                c.NatNumber.Contains(qry) || c.PhoneNumber.Contains(qry)).ToArray());
                        }
                        else if (DateTime.TryParse(qry, out dt))
                        {
                            arr.AddRange(q.Where(c => c.insertDate == dt).ToArray());
                        }
                        else
                        {
                            arr.AddRange(q.Where(c => (c.DisplayName.Contains(qry)
                                || c.CurrentAddress.Contains(qry) || c.OreginalAddress.Contains(qry))).ToArray());
                        }
                    }
                }
                listBoxWorthies.DataSource = arr.ToArray(typeof(ModelViews.WorthiesView));
            }
        }
        string Heading;
       
        string worthyNameTitle;

        private void listBoxWorthies_Click(object sender, EventArgs e)
        {
            if (tabControl1.SelectedTab == tabPageByWorthy)
            {
                rtb_records.Text = string.Empty;
                int id = (int)listBoxWorthies.SelectedValue;
                Worthy w = ctx.Worthies.Find(id);
                Person p = ctx.People.Find(w.PersonId);
                worthyId = p.WorthyId;
                // Font f = new System.Drawing.Font(new Font(,new FontFamily(FontStyle.Bold);
                rtb_records.AppendText(" \n", Color.Black, new System.Drawing.Font("Times New Roman", 14, FontStyle.Bold));
                rtb_records.AppendText(" \n" + " سجل تتبع مستحق " + "\n\n\n");
                Heading = "سجل تتبع مستحق";
                rtb_records.AppendText(" " + " إسم المستحق: ", Color.Red);
                worthyNameTitle = " إسم المستحق: ";
                rtb_records.AppendText(p.FirstName + " " + p.FatherName + " " + p.LastName + " ", Color.Black);
                rtb_records.AppendText(" رقم استمارة  المستحق : ", Color.Red);
                
                rtb_records.AppendText(" " + id + "\n", Color.Black);
                if (ctx.Users.Where(us => us.Id == p.InsertUId).Count() > 0)
                {
                    User u = ctx.Users.Where(us => us.Id == p.InsertUId).First();

                    rtb_records.AppendText(" " + " إسم مدخل البيانات: ", Color.Blue);
                    rtb_records.AppendText(" " + u.username, Color.Black);
                    rtb_records.AppendText(" " + " تاريخ ادخال البيانات", Color.Blue);
                    rtb_records.AppendText(" " + p.InsertDate.Value.ToString() + "\n", Color.Black);
                }

                if (ctx.Users.Where(ui => ui.Id == p.UpdateUId).Count() > 0)
                {
                    User uu = ctx.Users.Where(ui => ui.Id == p.UpdateUId).First();
                    rtb_records.AppendText(" " + " إسم آخر من عدل البيانات: ", Color.Blue);
                    rtb_records.AppendText(" " + uu.username, Color.Black);
                    rtb_records.AppendText(" " + " تاريخ آخر تعديل للبيانات", Color.Blue);
                    rtb_records.AppendText(" " + p.UpdateDate.Value.ToString() + "\n", Color.Black);
                }
                if (w.People.Count() > 1)
                {
                    rtb_records.AppendText("===============================================\n", Color.Black);
                    rtb_records.AppendText(" " + " معلومات الأقارب:  \n", Color.Red);
                    rtb_records.AppendText("===============================================\n", Color.Black);
                    foreach (var i in w.People)
                    {
                        rtb_records.AppendText(" " + " ادخال قريب: " + i.FirstName + " " + i.LastName + "\n");

                        if (ctx.Users.Where(us => us.Id == i.InsertUId).Count() > 0)
                        {
                            User u = ctx.Users.Where(us => us.Id == i.InsertUId).First();
                            rtb_records.AppendText(" " + " إسم مدخل البيانات: ", Color.Red);
                            rtb_records.AppendText(" " + u.username, Color.Black);
                            rtb_records.AppendText(" " + " تاريخ ادخال البيانات", Color.Red);
                            rtb_records.AppendText(" " + i.InsertDate.Value.ToString() + "\n", Color.Black);
                        }
                        if (ctx.Users.Where(ui => ui.Id == i.UpdateUId).Count() > 0)
                        {
                            User uu = ctx.Users.Where(ui => ui.Id == i.UpdateUId).First();
                            rtb_records.AppendText(" " + " إسم آخر من عدل البيانات: ", Color.Red);
                            rtb_records.AppendText(" " + uu.username, Color.Black);
                            rtb_records.AppendText(" " + " تاريخ آخر تعديل للبيانات", Color.Red);
                            rtb_records.AppendText(" " + i.UpdateDate.Value.ToString() + "\n", Color.Black);
                        }
                    }
                }


                if (w.Grants.Count() > 0)
                {
                    rtb_records.AppendText("===============================================\n", Color.Black);
                    rtb_records.AppendText(" " + " المنح المعطاة:  \n", Color.Red);
                    rtb_records.AppendText("===============================================\n", Color.Black);
                    foreach (var i in w.Grants)
                    {
                        rtb_records.AppendText(" " + " منحة برقم: " + i.IssueNumber + " بتاريخ: " + i.IssueDate.ToLongDateString() + "\n");

                        if (ctx.Users.Where(ui => ui.Id == i.InsertUId).Count() > 0)
                        {
                            User u = ctx.Users.Where(us => us.Id == i.InsertUId).FirstOrDefault();
                            rtb_records.AppendText(" " + " إسم مدخل البيانات: ", Color.Blue);
                            rtb_records.AppendText(" " + u.username, Color.Black);
                            rtb_records.AppendText(" " + " تاريخ ادخال البيانات", Color.Blue);
                            rtb_records.AppendText(" " + i.InsertDate.Value.ToString() + "\n", Color.Black);
                        }

                        if (ctx.Users.Where(ui => ui.Id == i.UpdateUId).Count() > 0)
                        {
                            User uu = ctx.Users.Where(ui => ui.Id == i.UpdateUId).FirstOrDefault();
                            rtb_records.AppendText(" " + " إسم آخر من عدل البيانات: ", Color.Blue);
                            rtb_records.AppendText(" " + uu.username, Color.Black);
                            rtb_records.AppendText(" " + " تاريخ آخر تعديل للبيانات", Color.Blue);
                            rtb_records.AppendText(" " + i.UpdateDate.Value.ToString() + "\n", Color.Black);
                        }
                    }
                }
                if (w.Needs.Count() > 0)
                {
                    rtb_records.AppendText("===============================================\n", Color.Black);
                    rtb_records.AppendText(" " + " ادخال الاحتياجات:  \n", Color.Red);
                    rtb_records.AppendText("===============================================\n", Color.Black);
                    foreach (var i in w.Needs)
                    {
                        rtb_records.AppendText(" " + " الإحتياج: " + i.SupplyType.Name + " : " + i.Description + "\n");

                        if (ctx.Users.Where(ui => ui.Id == i.InsertUId).Count() > 0)
                        {
                            User u = ctx.Users.Where(us => us.Id == i.InsertUId).FirstOrDefault();
                            rtb_records.AppendText(" " + " إسم مدخل البيانات: ", Color.Blue);
                            rtb_records.AppendText(" " + u.username, Color.Black);
                            rtb_records.AppendText(" " + " تاريخ ادخال البيانات", Color.Blue);
                            rtb_records.AppendText(" " + i.InsertDate.Value.ToString() + "\n", Color.Black);
                        }

                        if (ctx.Users.Where(ui => ui.Id == i.UpdateUId).Count() > 0)
                        {
                            User uu = ctx.Users.Where(ui => ui.Id == i.UpdateUId).FirstOrDefault();
                            rtb_records.AppendText(" " + " إسم آخر من عدل البيانات: ", Color.Blue);
                            rtb_records.AppendText(" " + uu.username, Color.Black);
                            rtb_records.AppendText(" " + " تاريخ آخر تعديل للبيانات", Color.Blue);
                            rtb_records.AppendText(" " + i.UpdateDate.Value.ToString() + "\n", Color.Black);
                        }
                    }
                }
            }
            else if (tabControl1.SelectedTab == tabPageByUser)
            {
                rtb_user_records.Text = string.Empty;
                int id = (int)ListBoxUsers.SelectedValue;
                User u = ctx.Users.Find(id);
                rtb_user_records.AppendText(" \n", Color.Black, new System.Drawing.Font("Times New Roman", 14, FontStyle.Bold));
                rtb_user_records.AppendText(" \n" + " سجل تتبع مستخدم " + "\n\n\n");
                Heading = "سجل تتبع مستخدم";
                rtb_user_records.AppendText(" " + " إسم المستخدم: ", Color.Red);
                worthyNameTitle = " إسم المستخدم: ";
                rtb_user_records.AppendText(u.username + " ", Color.Black);
                if (ctx.Worthies.Where(c=>(c.InsertUId==u.Id && dtp_toDate.Value>=c.InsertDate)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + " المستحقين:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Worthy> worthie = ctx.Worthies.Where(c => (c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate) || (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).ToList();
                    foreach (var i in worthie)
                    {
                        Person p = ctx.People.Single(c => c.Id == i.PersonId);
                        rtb_user_records.AppendText(" " + "  إدخال المستحق: " + p.FirstName +"  "+p.LastName + " :  " +" استمارة رقم: " + i.Id + "\n");
                    }
                }
                if (ctx.Worthies.Where(c => (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + " المستحقين:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Worthy> worthie = ctx.Worthies.Where(c => (c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate) || (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).ToList();
                    foreach (var i in worthie)
                    {
                        Person p = ctx.People.Single(c => c.Id == i.PersonId);
                        rtb_user_records.AppendText(" " + "  تعديل المستحق: " + p.FirstName + "  " + p.LastName + " :  " + " استمارة رقم: " + i.Id + "\n");
                    }
                }
                if (ctx.People.Where(c => ((c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate))&&(c.Id !=c.Worthy.PersonId)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + "  الأقارب إدخال:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Person> people = ctx.People.Where(c => ((c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate)) && (c.Id != c.Worthy.PersonId)).ToList();
                    foreach (var i in people)
                    {
                        rtb_user_records.AppendText(" " + "  إدخال  قريب: " + i.FirstName +"  " +i.LastName+" "+ " : " + "للمستحق" + i.WorthyId + "\n");
                    }
                }
                if (ctx.People.Where(c => (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate) && (c.Id != c.Worthy.PersonId)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + "  تعديل الأقارب:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Person> people = ctx.People.Where(c => (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate) && (c.Id != c.Worthy.PersonId)).ToList();
                    foreach (var i in people)
                    {
                        rtb_user_records.AppendText(" " + "  تعديل قريب: " + i.FirstName + "  " + i.LastName + " " + " : " + "للمستحق" + i.WorthyId + "\n");
                    }
                }
                if (ctx.Needs.Where(c => (c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + "  إدخال الاحتياجات:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Need> needs = ctx.Needs.Where(c => (c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate)).ToList();
                    foreach (var i in needs)
                    {
                        rtb_user_records.AppendText(" " + "  إدخال الإحتياج: " + i.SupplyType.Name + " : " + i.Description + "للمستحق" + i.WorthyId + "\n");
                    }
                }
                if (ctx.Needs.Where(c => (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + "  تعديل الاحتياجات:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Need> needs = ctx.Needs.Where(c => (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).ToList();
                    foreach (var i in needs)
                    {
                        rtb_user_records.AppendText(" " + "  تعديل الإحتياج: " + i.SupplyType.Name + " : " + i.Description + "للمستحق" + i.WorthyId + "\n");
                    }
                }
                if (ctx.Users.Where(c => (c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate) || (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + "  مستخدمين:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<User> needs = ctx.Users.Where(c=>(c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate) || (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).ToList();
                    foreach (var i in needs)
                    {
                        rtb_user_records.AppendText(" " + "  إدخال /تعديل مستخدم: " + i.username + "\n");
                    }
                }
                if (ctx.Supplies.Where(c => (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + "  تعديل إعدادات المعونات:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Supply> needs = ctx.Supplies.Where(c => (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).ToList();
                    foreach (var i in needs)
                    {
                        rtb_user_records.AppendText(" " + "  تعديل المعونة: " + i.Name + " : " + "\n");
                    }
                }
                if (ctx.Supplies.Where(c => (c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + "  إدخال إعدادات المعونات:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Supply> needs = ctx.Supplies.Where(c => (c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate)).ToList();
                    foreach (var i in needs)
                    {
                        rtb_user_records.AppendText(" " + "  إدخال المعونة: " + i.Name + " : " + "\n");
                    }
                }
                if (ctx.Grants.Where(c => (c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + "  إدخال المنح:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Grant> needs = ctx.Grants.Where(c => (c.InsertUId == u.Id && dtp_toDate.Value >= c.InsertDate)).ToList();
                    foreach (var i in needs)
                    {
                        rtb_user_records.AppendText(" " + "   إدخال المنحة برقم : " + i.IssueNumber +" بتاريخ "+i.IssueDate.Date.ToShortDateString() +" للاستمارة رقم  "+i.WorthyId+ " : " + "\n");
                    }
                }
                if (ctx.Grants.Where(c => (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).Count() > 0)
                {
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    rtb_user_records.AppendText(" " + "  تسليم المنح:  \n", Color.Red);
                    rtb_user_records.AppendText("===============================================\n", Color.Black);
                    List<Grant> needs = ctx.Grants.Where(c => (c.UpdateUId == u.Id && dtp_toDate.Value >= c.UpdateDate)).ToList();
                    foreach (var i in needs)
                    {
                        rtb_user_records.AppendText(" " + "   تسليم المنحة برقم : " + i.IssueNumber + " بتاريخ " + i.IssueDate.Date.ToShortDateString() + " للاستمارة رقم  " + i.WorthyId + " : " + "\n");
                    }
                }

            


            }
            
        }

        private void txb_search_TextChanged(object sender, EventArgs e)
        {
            GetWorthiesNames();
        }

        private void btn_Print_Click(object sender, EventArgs e)
        {
            PrintDialog print = new PrintDialog();
            PrintDocument doc = new System.Drawing.Printing.PrintDocument();
            
            print.Document = doc;
            doc.PrintPage += new System.Drawing.Printing.PrintPageEventHandler(printDoc);
            if (print.ShowDialog() == DialogResult.OK)
            {
                doc.Print();
            }
        }
        private void printDoc(object sender, System.Drawing.Printing.PrintPageEventArgs e)
        {
            System.IO.StringReader reader = new System.IO.StringReader(rtb_records.Text);
            float linesPerPage = 0;
            float yPosition = 0;
            int count = 0;
            float leftMargin = e.MarginBounds.Left;
            float rightMargin = e.MarginBounds.Right;
            float topMargin = e.MarginBounds.Top;
            string line = null;
            System.Drawing.Font printFont = this.rtb_records.Font;
            SolidBrush printBrush = new SolidBrush(Color.Black);
            int charpos = 0;
            int xPosition = (int)leftMargin;

            linesPerPage = e.MarginBounds.Height / printFont.GetHeight(e.Graphics);

            while (count < linesPerPage && ((line = reader.ReadLine()) != null))
            {
                xPosition = (int)leftMargin;
                yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
                count++;
                for (int i = 0; i < line.Length; i++)
                {
                    rtb_records.Select(charpos, 1);
                    if ((xPosition + ((int)e.Graphics.MeasureString(rtb_records.SelectedText, rtb_records.SelectionFont).Width)) > rightMargin)
                    {
                        count++;
                        if (!(count < linesPerPage))
                        {
                            break;
                        }
                        xPosition = (int)leftMargin;
                        yPosition = topMargin + (count * printFont.GetHeight(e.Graphics));
                    }
                    printBrush = new SolidBrush(rtb_records.SelectionColor);
                    e.Graphics.DrawString(rtb_records.SelectedText, rtb_records.SelectionFont, printBrush, new PointF(xPosition, yPosition));
                    xPosition += ((int)e.Graphics.MeasureString(rtb_records.SelectedText, rtb_records.SelectionFont).Width);
                    charpos++;
                }
            }

            if (line != null)
            {
                e.HasMorePages = true;
            }
            else
            {
                e.HasMorePages = false;
                printBrush.Dispose();
            }
        }
        private void btn_Dispose_Click(object sender, EventArgs e)
        {
            this.Close();
            is_loaded = false;
        }

        private void btn_SaveAs_Click(object sender, EventArgs e)
        {
            sfd.ShowDialog();       
        }

        private void sfd_FileOk(object sender, CancelEventArgs e)
        {
            if (sfd.FileName.EndsWith(".doc") || sfd.FileName.EndsWith(".rtf"))
            {
                Microsoft.Office.Interop.Word.Application app = new Microsoft.Office.Interop.Word.Application();
                app.Visible = true;

                // save the contents of the rtf file to a temporary file
                object dir = sfd.FileName;
                rtb_records.SaveFile(dir.ToString());
                // open the rtf file inside of Microsoft Word
                object typeMissing = Type.Missing;
                object trueIndicator = true;
                app.Documents.Open(ref dir, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing, ref trueIndicator, ref typeMissing, ref typeMissing, ref typeMissing, ref typeMissing);
            }
            else if (sfd.FileName.EndsWith(".pdf"))
            {

                iTextSharp.text.Document doc = new iTextSharp.text.Document();
                PdfWriter.GetInstance(doc, new FileStream(sfd.FileName, FileMode.Create));
                PdfPTable table = new PdfPTable(1);
                table.RunDirection = PdfWriter.RUN_DIRECTION_RTL;
                table.DefaultCell.NoWrap = false;
                //Full path to the Unicode Arial file
                string ARIALUNI_TFF = Path.Combine("C:\\", "ARIAL.TTF");

                //Create a base font object making sure to specify IDENTITY-H
                BaseFont bf = BaseFont.CreateFont(ARIALUNI_TFF, BaseFont.IDENTITY_H, BaseFont.NOT_EMBEDDED);
                iTextSharp.text.Font fHeading = new iTextSharp.text.Font(bf, 12,1,BaseColor.RED);

                //Create a base font object making sure to specify IDENTITY-H
                iTextSharp.text.Font fHeading1 = new iTextSharp.text.Font(bf, 12, 0, BaseColor.BLACK);
                if (Heading.Length>0)
                {
                    rtb_records.Text = rtb_records.Text.Substring(rtb_records.Text.IndexOf(Heading) + Heading.Length, rtb_records.Text.Length - (rtb_records.Text.IndexOf(Heading) + Heading.Length));
                    PdfPCell Headingtext = new PdfPCell(new Phrase(Heading, fHeading));
                    Headingtext.BorderColor = BaseColor.WHITE;
                    rtb_records.Text = rtb_records.Text.Substring(rtb_records.Text.IndexOf(worthyNameTitle) + worthyNameTitle.Length, rtb_records.Text.Length - (rtb_records.Text.IndexOf(worthyNameTitle) + Heading.Length));
                    PdfPCell wotext = new PdfPCell(new Phrase(worthyNameTitle, fHeading));
                    wotext.BorderColor = BaseColor.WHITE;
                    PdfPCell textBody = new PdfPCell(new Phrase(rtb_records.Text, fHeading1));
                    textBody.BorderColor = BaseColor.WHITE;
                    //Ensure that wrapping is on, otherwise Right to Left text will not display
                    Headingtext.NoWrap = false;
                    wotext.NoWrap = false;
                    textBody.NoWrap = false;
                    //Add the cell to the table
                    table.AddCell(Headingtext);
                    table.AddCell(wotext);
                    table.AddCell(textBody);
                    //Add the table to the document
                    doc.Open();
                    doc.Add(table);
                    doc.Close();
                }
            }

        }

        private void tabControl1_SelectedIndexChanged(object sender, EventArgs e)
        {
            GetWorthiesNames();
        }

        private void TrackWorthyUserForm_FormClosed(object sender, FormClosedEventArgs e)
        {
            is_loaded = false;
            // remove this form from windows list
            ((Forms.FormMDI)fo).removeFormFromWindowsList(this);
        }

        private void TrackWorthyUserForm_Activated(object sender, EventArgs e)
        {
            // activate this form and add it windows list as activate one
            ((Forms.FormMDI)this.MdiParent).activateWindow(this);
        }
    }
    public static class RichTextBoxExtensions
    {
        public static void AppendText(this RichTextBox box, string text, Color color)
        {
            box.SelectionStart = box.TextLength;
            box.SelectionLength = 0;
            box.SelectionColor = color;
            box.AppendText(text);
            box.SelectionColor = box.ForeColor;
        }
        public static void AppendText(this RichTextBox box, string text, Color color,System.Drawing.Font font)
        {
            box.SelectionStart = box.TextLength;
            box.SelectionLength = 0;
            box.SelectionColor = color;
            box.AppendText(text);
            box.SelectionColor = box.ForeColor;
            box.SelectionFont = font;
        }
    }
}